package com.ml.room.terrace.pipeline;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.ml.room.dao.IBuildingRecordDao;
import com.ml.room.repository.entity.BuildingProjectItem;
import com.ml.room.service.IBuildingProjectItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.Set;

/**
 * @ClassName: BuildingProjectItemPagePipeline
 * @Decription: 此处填写类文件说明
 * @Author: IDai
 * @Date: 2021-09-01 16:36 星期三
 **/
@Component
public class BuildingProjectItemPagePipeline implements Pipeline {
    @Autowired
    private IBuildingRecordDao buildingRecordDao;
    @Autowired
    private IBuildingProjectItemService buildingProjectItemService;

    public int infoStatus = 0;

    public int getInfoStatus() {
        return infoStatus;
    }

    public void setInfoStatus(int infoStatus) {
        this.infoStatus = infoStatus;
    }

    /** 日志打印工具 **/
    private static final Logger logger = LoggerFactory.getLogger(BuildingProjectItemPagePipeline.class);

    @Override
    public void process(ResultItems resultItems, Task task) {
        logger.info("【合肥新房】 - 楼房详情 - 待入库的数据是，resultItems：{}", JSON.toJSONString(resultItems.get("projectItems")));
        boolean isFinish = resultItems.get("isFinish");
        if (isFinish){
            //如果已经抓取完成，则更新楼房抓取状态
            buildingRecordDao.finishCollarProjectItemData(resultItems.get("recordId"));
            infoStatus = 1;
            logger.info("【合肥新房】 - 楼房详情 - 备案号：{}，数据抓取完成！",(String)resultItems.get("recordId"));
        }else{
            Set<BuildingProjectItem> projectItems = resultItems.get("projectItems");
            if (CollectionUtil.isNotEmpty(projectItems)){
                //如果不为重复数据，保存楼房详情数据
                boolean flag = buildingProjectItemService.saveBatch(projectItems);
                if (flag){
                    //批量保持成功，更新抓取的页码。
                    int result = buildingRecordDao.updateCollarPageById(resultItems.get("recordId"));
                    if (result == 1){
                        //同步页面成功，即将开始下一页的抓取
                        logger.info("【合肥新房】 - 楼房详情 - 处理结果：{}", "数据抓取完成,即将开始下一页的抓取...");
                    }
                }
            }else {
                int result = buildingRecordDao.updateCollarPageById(resultItems.get("recordId"));
                if (result == 1){
                    //同步页面成功，即将开始下一页的抓取
                    logger.info("【合肥新房】 - 楼房详情 - 处理结果：{}", "重复数据,即将开始下一页的抓取...");
                }
            }
        }
    }
}
